/*
 * Copyright (c) 2017. 恒昌互联网运营中心.
 */
package com.credithc.eagleeye.console.mail;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SendFileMail {
    private static final Logger log = LoggerFactory.getLogger(SendFileMail.class);
    public static boolean sendMail(String subject, String sender, String receiver, String msg, String attachName)
            throws Exception {
        if (StringUtils.isBlank(receiver)) {
            throw new Exception("Email receiver is null");
        }
        String receiverGroup[] = StringUtils.split(receiver,",");
        return sendMail(subject, sender, receiverGroup, msg, attachName);
    }

    public static boolean sendMail(String subject, String sender, String receivers[], String msg, String attachName)
            throws Exception {

        log.debug("sendMail .... Start: subject = [" + subject + "], sender = [" + sender + "], receivers = [" + receivers + "]" + ", msg = [" + msg + "], attachName = " + attachName + "]");
        if ((subject == null) || (msg == null)) {
            throw new Exception("Email subject or content is null");
        }
        if (StringUtils.isBlank(sender)) {
            throw new Exception("Email sender is null");
        }
        if (receivers==null ||receivers.length==0 ) {
            throw new Exception("Email receiver is null");
        }
        boolean isSuccess = false;
        try {
            MultiPartEmail email = new MultiPartEmail();
            email.setHostName(MailConfig.MAIL_SMTP_ADDRESS);
            email.setAuthentication(MailConfig.MAIL_SENDER_USER, MailConfig.MAIL_SENDER_PASSWORD);

            for(String receiver : receivers) {
                email.addTo(receiver, receiver);
            }

            email.setFrom(MailConfig.MAIL_SENDER_USER, sender);
            email.setCharset("UTF-8");
            email.setSubject(subject);
            email.setMsg(msg);
            if ((attachName != null) && (attachName.trim().length() > 0)) {
                EmailAttachment attachment = new EmailAttachment();
                attachment.setPath(attachName);
                attachment.setDisposition("attachment");
                email.attach(attachment);
            }
            email.send();
            isSuccess = true;
        } catch (EmailException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        log.debug("sendMail .... End: subject = [" + subject + "]");
        return isSuccess;
    }
}